package musicstore.aop;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import musicstore.entity.User;

import org.aspectj.lang.JoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class MyAdvice {
	

//    @Autowired  
//    //Session
//    private HttpSession session;  
      
    @Autowired
    //request
    private HttpServletRequest request;  

	
	public void doAfterReturn(JoinPoint jp){
		Date date = new Date();
		String packageName = jp.getTarget().getClass().getName();
		String methodName = jp.getSignature().getName();
		String name = "匿名用户";
		//也可以使用ActionContext来获取Session
		if(RequestContextHolder.getRequestAttributes()!=null){
	    request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();   
		User user = (User) request.getSession().getAttribute("user");
		if(user != null)
			name = user.getUsername();
		}
		
	    String daily = date+"--"+name+"执行了"+packageName+"类的"+methodName+"方法";
		File file = new File("C:\\程序设计\\作业\\it_homework\\musicstore\\src\\main\\MusicStoreBizLog.txt");
		try {
			Writer write = new FileWriter(file,true);
			BufferedWriter bw = new BufferedWriter(write);
			bw.write(daily);
			bw.newLine();
			bw.flush();
			bw.close();
			write.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
